from functools import wraps
from flask import abort
from flask_login import current_user
from app_db import db
from src.db_init import init
from src.model.models import Role
from config import config


def permission_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not current_user.can(permission):
                abort(403)
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def admin_required(f):
    try:
        role = Role.query.filter_by(is_valid=1, name=config.ADMIN_ROLE).first()
    except Exception:
        db.create_all()
        init()
        role = Role.query.filter_by(is_valid=1, name=config.ADMIN_ROLE).first()
    return permission_required(permission=role.id)(f)
